import React from "react";
import { inject, observer } from "mobx-react";
import { commonStyles } from "../../configs/commonStyle";
import { Image, Platform, StyleSheet, Vibration } from "react-native";
import { NAV_BAR_HEIGHT_ANDROID, NAV_BAR_HEIGHT_IOS, windowWidth } from "../../configs/platform";
import BasePage from "../BasePage";
import { TouchableOpacity, View } from "react-native-ui-lib";
import navigator from "../../utils/navigator";
import ImagePicker from "react-native-image-crop-picker";
import { checkStorePermission, logger, uploadError } from "../../utils/util";
import PermissionDialog from "../common/PermissionDialog";
import { readerQR } from "react-native-lewin-qrcode";
import { getStatusBarHeight } from "react-native-status-bar-height";
import { Icon } from "../components";
import { IconImage } from "../../utils";
import api from "../../net/api";
import ToastUtils from "../../utils/ToastUtils";
import { CameraScreen } from "react-native-camera-kit";
import Events from "../../utils/events";
import moment from 'moment';
import _ from 'lodash';

/**
 * 扫一扫
 */
@inject("userStore", "appStore")
@observer
export default class ScanPage extends BasePage {

  constructor(props) {
    super(props);
    this.lastTime = 0;
    this.canScan = true;
    this.state = {
      flashImage: IconImage.ic_light_off,
      flashMode: "off",
    };
  }

  qrcode = (data) => {
    if (this.canScan == false) {
      return;
    }
    //震动
    Vibration.vibrate();
    this.canScan = false;
    this.addDeliveryScanLog(data).finally(() => {
      this.canScan = true;
    });
  };

  openAlbum = () => {
    const checkPermission = checkStorePermission();
    if (checkPermission == false) {
      this.permissionDialog.show("识别图片需要获得存储，请开启");
      return;
    }
    ImagePicker.openPicker({}).then(res => {
      logger("选择图片路径", res);
      readerQR(res.path).then((data) => {
        Log("识别结果", data);
        this.qrcode(data);
      }).catch((err) => {
        Log("识别失败", err);
        this.showToast("识别失败");
      });
    }).catch(e => {
      logger(e);
    });
  };

  changeFlashMode = () => {
    const { flashMode } = this.state;
    if (flashMode == "off") {
      this.setState({ flashImage: IconImage.ic_light_on, flashMode: "on" });
    } else if (flashMode == "on") {
      this.setState({ flashImage: IconImage.ic_light_off, flashMode: "off" });
    }
    this.camera.onSetTorch();
  };

  addDeliveryScanLog = (orderDetailId) => {
    logger("订单号", orderDetailId);
    const { from, ordNo } = this.props.navigation.state.params;
    const { userInfo } = this.props.userStore;
    let params = {
      token: global.token,
      distributorId: userInfo.distributorId,
      orderDetailId,
      orderId: ordNo,
      scanTime: moment().format("YYYY-MM-DD HH:mm:ss"),
      showLoading: true,
    };
    return axios.get(api.addDeliveryScanLog, { params })
      .then(res => {
        if (ordNo && ordNo != res.result.ordNo) {
          ToastUtils.showFailInfo("拿错蛋糕了，请仔细检查");
          return;
        }

        ToastUtils.showSuccessInfo("扫码成功");
        Events.publish("RefreshOrderList");
        this._onBackPress()
      }).catch(e => {
        e.msg && ToastUtils.showFailInfo(e.msg);
        uploadError("扫码调用addDeliveryScanLog失败", `参数：${JSON.stringify(params)},${e.msg}`);
      })
  };

  /**
   * 立即配送
   * @param item
   */
  deliveryOrder = (ordNo) => {
    axios.get(api.deliveryOrder, {
      params: {
        ordNo,
        showLoading: true,
        token: global.token,
      },
    })
      .then(result => {
        navigator.replace("OrderDetails", { ordNo });
      }).catch((e) => {
      logger(e);
      e.msg && ToastUtils.showFailInfo(e.msg);
      this.canScan = true;
    });
  };

  // 摄像机识别
  onCameraScreen = _.throttle((event) => {
    const result = event && event.nativeEvent &&  event.nativeEvent.codeStringValue
    logger("识别结果", result);
    if (result) {
      const orderInfo = JSON.parse(result)
      if (orderInfo) {
        if (orderInfo.orderDetailId) {
          this.qrcode(orderInfo.orderDetailId);
        } else {
          this.qrcode(orderInfo);
        }
      } else {
        ToastUtils.showFailInfo(`无效二维码：${result}`);
      }
    }
  }, 800)

  render() {
    const { flashImage } = this.state;
    return (
      <View useSafeArea style={{ flex: 1, backgroundColor: "black" }}>
        <View flex>
          <CameraScreen
            ref={r => this.camera = r}
            scanBarcode
            onReadCode={this.onCameraScreen}
            showFrame={true}
            laserColor={"yellow"}
            frameColor={"white"}
          />
        </View>
        <View useSafeArea style={styles.title}>
          <TouchableOpacity style={styles.navBar}
                            onPress={this._onBackPress}>
            <Icon type="AntDesign" name={"left"} color={"white"} size={21} />
          </TouchableOpacity>
          <View row centerV>
            {/*<TouchableOpacity style={styles.navBar}*/}
            {/*                  onPress={this.openAlbum}>*/}
            {/*  <Image source={IconImage.ic_photos} style={{ width: 21, height: 21 }} />*/}
            {/*</TouchableOpacity>*/}
            <TouchableOpacity style={styles.navBar}
                              onPress={this.changeFlashMode}>
              <Image source={flashImage} style={{ width: 21, height: 21, marginLeft: 10 }} />
            </TouchableOpacity>
          </View>
        </View>
        <PermissionDialog ref={r => this.permissionDialog = r} />
      </View>
    );
  }
}


const styles = StyleSheet.create({
  bottomContentView: {
    height: 50,
    flexDirection: "row",
    backgroundColor: "black",
    justifyContent: "center",
    alignItems: "center",
    position: "absolute",
    left: 0,
    bottom: 0,
    zIndex: 100,
    width: windowWidth,
  },
  container: { flex: 1, alignItems: "center", justifyContent: "flex-end", paddingBottom: 20 },
  desc: {
    backgroundColor: "rgba(0,0,0,0.5)",
    borderRadius: 2,
    marginTop: 20,
    paddingHorizontal: 20,
    paddingVertical: 5,
  },
  navBar: {
    alignItems: "center",
    justifyContent: "center",
    height: Platform.OS === "ios" ? NAV_BAR_HEIGHT_IOS : NAV_BAR_HEIGHT_ANDROID,
  },
  title: {
    ...commonStyles.navBar,
    backgroundColor: "transparent",
    position: "absolute",
    left: 0,
    right: 0,
    top: 0,
    marginTop: getStatusBarHeight(),
  },
  bottomWrap: {
    position: "absolute",
    left: 0,
    right: 0,
    bottom: 0,
    ...commonStyles.center,
  },
});
